package com.yixun.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixun.entity.YwDiQu;
import com.yixun.entity.YxUser;
import com.yixun.mapper.YwDiQuMapper;
import com.yixun.service.LogSetService;
import com.yixun.service.RedisService;
import com.yixun.service.YwDiQuService;
import com.yixun.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class YwDiQuServiceImpl implements YwDiQuService {

    @Autowired
    private YwDiQuMapper ywDiQuMapper;

    @Autowired
    private LogSetService logSetService;

    @Autowired
    private RedisService redisService;

    @Override
    public String getDqNameByDqYwId(Long dq_yw_id) {
        return ywDiQuMapper.getDqNameByDqYwId(dq_yw_id);
    }

    @Override
    public String getYwDiquTree(Long dq_yw_id) {

        List<YwDiQu> all_list = ywDiQuMapper.getAllYwDiQuList();
        YwDiQu ywDiQu = ywDiQuMapper.getYwDiQuBean(dq_yw_id);
        if (null != ywDiQu) {
            String json_str = "[{\"id\":\"" + dq_yw_id + "\",\"text\":\""
                    + ywDiQu.getDq_name() + "\",\"attributes\":{\"level\":\""+ywDiQu.getDq_level()+"\"}";
            String child_str = getYwDiquTreeHandle(getChildYwDiquList(all_list, ywDiQu.getDq_yw_id()), all_list);
            if (child_str != null && !"".equals(child_str)) {
                json_str += ",\"children\":[" + child_str + "]";
            }
            json_str += "}]";
            redisService.setYwDiQuTree("YwDiQuTree", json_str);
            return json_str;
        } else {
            return "[]";
        }
    }

    @Override
    public String getAllChildYwDiquTree(Long dq_yw_id) {
        YwDiQu ywDiQu = ywDiQuMapper.getYwDiQuBean(dq_yw_id);
        if (null != ywDiQu) {
            List<YwDiQu> all_list = ywDiQuMapper.getAllYwDiQuList();
            String child_str = getAllYwDiquTreeHandle(getChildYwDiquList(all_list,dq_yw_id), all_list);
            return "["+child_str+"]";
        } else {
            return "[]";
        }
    }

    @Override
    public List<YwDiQu> getChildYwDiquList(Long parent_id) {
        return ywDiQuMapper.getChildYwDiquList(parent_id);
    }

    @Override
    public YwDiQu getYwDiQuBean(Long dq_yw_id) {
        return ywDiQuMapper.getYwDiQuBean(dq_yw_id);
    }

    @Override
    @Transactional
    public int insertYwDiQu(YxUser sessionUser, YwDiQu ywDiQu) {
        int row = 0;
        String tree_position = ywDiQuMapper.getTreePosition(ywDiQu.getParent_id());
        ywDiQu.setTree_position(tree_position + ywDiQu.getDq_yw_id() + "$");
        row = ywDiQuMapper.insertYwDiQu(ywDiQu);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.ADD, "业务地区", JSON.toJSONString(ywDiQu), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int updateYwDiQu(YxUser sessionUser, YwDiQu ywDiQu) {
        int row = 0;
        row = ywDiQuMapper.updateYwDiQu(ywDiQu);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.UPDATE, "业务地区", JSON.toJSONString(ywDiQu), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int delYwDiQu(YxUser sessionUser, String id) {
        int row = 0;
        String[] ids = id.split(",");
        for (String yw_dq_id: ids) {
            String treePosition = ywDiQuMapper.getTreePosition(Long.parseLong(yw_dq_id));
            ywDiQuMapper.delYwDiQu(treePosition);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.DELETE, "业务地区", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int moveYwDiQu(YxUser sessionUser, Map map) {
        int row = 0;
        String parent_id = (String) map.get("parent_id");
        String dq_yw_ids = (String) map.get("dq_yw_ids");
        String treePosition = ywDiQuMapper.getTreePosition(Long.parseLong(parent_id));
        if (null != dq_yw_ids && !"".equals(dq_yw_ids)) {
            String[] tempA = dq_yw_ids.split(",");
            for (int i = 0; i < tempA.length; i++) {
                moveYwDiquHandle(tempA[i], parent_id, treePosition);
                row++;
            }
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.MOVE,"业务地区", JSON.toJSONString(map), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int sortYwDiQu(YxUser sessionUser, String id) {
        int row = 0;
        Map<String, String> map = new HashMap<>();
        String[] ids = id.split(",");
        for (int i = 0; i < ids.length; i++) {
            map.put("sort_id", (i + 1) + "");
            map.put("dq_yw_id", ids[i]);
            ywDiQuMapper.sortDiQu(map);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.SAVE_SORT,"业务地区", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }


    /*=======================================moveYwDiquHandle===============================================*/

    public void moveYwDiquHandle(String dq_yw_id, String parent_id, String treePosition){
        String tree_position = treePosition + dq_yw_id + "$";
        Map<String, String> map = new HashMap<>();
        map.put("dq_yw_id",dq_yw_id);
        map.put("parent_id", parent_id);
        map.put("tree_position", tree_position);
        if (ywDiQuMapper.moveYwDiQu(map) > 0) {
            List<YwDiQu> childYwDiquList = getChildYwDiquList(Long.parseLong(dq_yw_id));
            if (null != childYwDiquList && childYwDiquList.size() > 0) {
                for (YwDiQu ywDiQu: childYwDiquList) {
                    moveYwDiquHandle(ywDiQu.getDq_yw_id()+"", dq_yw_id, tree_position);
                }
            }
        }
    }

    /*=======================================moveYwDiquHandle===============================================*/


    /*===================================================YwDiQu_Tree_Util=============================================================*/

    public String getYwDiquTreeHandle(List<YwDiQu> dl, List<YwDiQu> all_list){
        String json_str = "";
        if (null != dl && dl.size() > 0) {
            String child_state = "";
            for (YwDiQu ydq: dl) {
                if (ydq.getDq_level() < 4) {
                    if (ydq.getDq_level() < 1) {
                        child_state = "\"state\":\"opened\",";
                    } else {
                        child_state = "\"state\":\"closed\",";
                    }
                    json_str += ",{";
                    json_str += "\"id\":\"" + ydq.getDq_yw_id() + "\","
                            + "\"text\":\"" + ydq.getDq_name()+ "\","+child_state+"\"attributes\":{\"level\":\""+ydq.getDq_level()+"\"}";
                    String child_str = getYwDiquTreeHandle(getChildYwDiquList(all_list,ydq.getDq_yw_id()), all_list);
                    if (child_str != null && !"".equals(child_str)) {
                        json_str += ",\"children\":[" + child_str + "]";
                    }
                    json_str += "}";
                }
            }
            if (json_str != null && !"".equals(json_str)) {
                json_str = json_str.substring(1);
            }
        }
        return json_str;
    }

    public List<YwDiQu> getChildYwDiquList(List<YwDiQu> all_list,Long parent_id){
        List<YwDiQu> child_list = new ArrayList<>();
        for (YwDiQu ydq: all_list) {
            if (parent_id.equals(ydq.getParent_id())) {
                child_list.add(ydq);
            }
        }
        return child_list;
    }

    public String getAllYwDiquTreeHandle(List<YwDiQu> dl, List<YwDiQu> all_list){
        String json_str = "";
        if (null != dl && dl.size() > 0) {
            for (YwDiQu ydq: dl) {
                json_str += ",{";
                json_str += "\"id\":\"" + ydq.getDq_yw_id() + "\","
                        + "\"text\":\"" + ydq.getDq_name()+ "\",\"attributes\":{\"level\":\""+ydq.getDq_level()+"\"}";
                String child_str = getAllYwDiquTreeHandle(getChildYwDiquList(all_list,ydq.getDq_yw_id()), all_list);
                if (child_str != null && !"".equals(child_str)) {
                    json_str += ",\"children\":[" + child_str + "]";
                }
                json_str += "}";
            }
            if (json_str != null && !"".equals(json_str)) {
                json_str = json_str.substring(1);
            }
        }
        return json_str;
    }

    /*===================================================YwDiQu_Tree_Util=============================================================*/
}
